//
//  SDHSportsRegisterAndLoginVC.m
//  SDHSportsNews
//
//  Created by MichaelShan on 2021/3/11.
//

#import "SDHSportsRegisterAndLoginVC.h"
#import "UnderLineTextField.h"
#import "IQKeyboardManager.h"
#import "SDHSportsUserModel.h"
#import <objc/runtime.h>
#import "SDHSportsDataManager.h"
#import "SDHSportsNetRequest.h"
#import "SDHSportsRequest.h"

@interface SDHSportsRegisterAndLoginVC ()

@property (weak, nonatomic) IBOutlet UILabel *lbTip;
@property (weak, nonatomic) IBOutlet UIView *viewRegisterBg;
@property (weak, nonatomic) IBOutlet UnderLineTextField *tfFullname;
@property (weak, nonatomic) IBOutlet UnderLineTextField *tfEmail;
@property (weak, nonatomic) IBOutlet UnderLineTextField *tfMobile;
@property (weak, nonatomic) IBOutlet UnderLineTextField *tfPwd;
@property (weak, nonatomic) IBOutlet UIButton *btnSignup;
@property (weak, nonatomic) IBOutlet UILabel *lbLoginTip;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *vHeightCon;
@property (weak, nonatomic) IBOutlet UIImageView *imgBgView;
@property (weak, nonatomic) IBOutlet UIImageView *imgHello;
@property (weak, nonatomic) IBOutlet UILabel *lbForgetPwd;

@property (nonatomic, strong) SDHSportsUserModel *user;

@end

@implementation SDHSportsRegisterAndLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _user = [[SDHSportsUserModel alloc] init];
    [self initUI];
    [self updateUIDesc];
    [self setupKeyboardManager];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
}

- (void)signAction:(id)sender {
    
    // test account, 123456789, 123456
    if (_tfMobile.text.length == 0) {
        [MBProgressHUD showError:@"please input mobile"];
        return;
    }
    if (_tfPwd.text.length == 0) {
        [MBProgressHUD showError:@"please input full name"];
        return;
    }
    if (ViewTypeRegister == _viewType || ViewTypeForgetPwd == _viewType) {
        if (_tfEmail.text.length == 0) {
            [MBProgressHUD showError:@"please input code"];
            return;
        }
        if (_tfFullname.text.length == 0) {
            [MBProgressHUD showError:@"please input password"];
            return;
        }
    }
    
    if (ViewTypeLogin == _viewType) {
        [self login];
    }
}

- (void)login {
    NSString *testAccount = @"123456789";
    NSString *testPwd = @"123456";
    _user.phone = _tfMobile.text;
    _user.password = _tfPwd.text;
    
    [MBProgressHUD showLoading];
    // 延迟3s，登录成功
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([_tfMobile.text caseInsensitiveCompare:testAccount] == NSOrderedSame &&
            [_tfPwd.text caseInsensitiveCompare:testPwd] == NSOrderedSame) {
            [self loginSucceed];
        } else {
            [MBProgressHUD showError:@"Your account or password is incorrect, please input again"];
        }
    });
    
    SDHSportsRequest *request = [[SDHSportsRequest alloc] init];
    request.requestUrl = @"http://jsuywu8.com/guojitiyu/Tiyu1/login";
    request.requestPara = @{@"name":_tfMobile.text, @"pwd":_tfPwd.text};
    [[SDHSportsNetRequest sharedRequest] postRequest:request returnValueBlock:nil errorBlock:nil failureBlock:nil];
}

- (void)loginSucceed {
    [SDHSportsDataManager sharedManager].user = _user;
    [MBProgressHUD hideHUD];
    
    [self.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"login_succeed" object:_user];
}

- (void)updateUIDesc {
    if (ViewTypeLogin == _viewType) {
        _lbForgetPwd.hidden = NO;
    } else {
        _lbForgetPwd.hidden = YES;
    }
    
    if (ViewTypeRegister == _viewType || ViewTypeForgetPwd == _viewType) {
        _tfEmail.hidden = NO;
        _tfFullname.hidden = NO;
    } else {
        _tfEmail.hidden = YES;
        _tfFullname.hidden = YES;
    }
    
    NSString *title = @"Sign in";
    if (ViewTypeRegister == _viewType) {
        _lbLoginTip.text = @"Already have an account? Go login";
        title = @"Sign up";
    } else if (ViewTypeLogin == _viewType) {
        title = @"Sign in";
        _lbLoginTip.text = @"No account login yet? go to register";
    } else {
        title = @"Retrieve password";
        _lbLoginTip.text = @"Already have an account? Go login";
    }
    
    NSString *tipDesc = @"Sign up";
    if (ViewTypeLogin == _viewType) {
        tipDesc = @"Sign in to your account";
    } else if (ViewTypeRegister == _viewType) {
        tipDesc = @"Sign up";
    } else if (ViewTypeForgetPwd == _viewType) {
        tipDesc = @"Retrieve password";
    }
    _lbTip.text = tipDesc;
    
    self.title = title;
    [_btnSignup setTitle:title forState:UIControlStateNormal];
    [_btnSignup setTitle:title forState:UIControlStateSelected];
    [_btnSignup setTitle:title forState:UIControlStateHighlighted];
    [_btnSignup addTarget:self action:@selector(signAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    if (ViewTypeLogin == _viewType) {
        _tfEmail.returnKeyType = UIReturnKeyNext;
        _tfPwd.returnKeyType = UIReturnKeyGo;
    } else {
        _tfFullname.returnKeyType = UIReturnKeyNext;
        _tfEmail.returnKeyType = UIReturnKeyNext;
        _tfMobile.returnKeyType = UIReturnKeyNext;
        _tfPwd.returnKeyType = UIReturnKeyGo;
    }
    
    if (ViewTypeRegister == _viewType || ViewTypeForgetPwd == _viewType) {
        [UIView animateWithDuration:0.3 animations:^{
            _vHeightCon.constant = 500;
            [_tfMobile mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(120);
            }];
            [_tfPwd mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_tfMobile.mas_bottom).offset(120);
            }];
            [_viewRegisterBg.superview layoutIfNeeded];
        }];
    } else {
        [UIView animateWithDuration:0.3 animations:^{
            _vHeightCon.constant = 350;
            [_tfMobile mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(50);
            }];
            [_tfPwd mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_tfMobile.mas_bottom).offset(50);
            }];
            [_viewRegisterBg.superview layoutIfNeeded];
        }];
    }
}

- (void)initUI {
    
    _imgBgView.contentMode = UIViewContentModeScaleToFill;
    [_imgBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.equalTo(_viewRegisterBg.mas_top);
    }];
    
    _lbTip.textColor = [UIColor whiteColor];
    [_lbTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.viewRegisterBg.mas_top).offset(-50);
        make.centerX.mas_equalTo(0);
    }];
    _imgHello.image = [UIImage imageNamed:@"Hello"];
    _imgHello.contentMode = UIViewContentModeScaleToFill;
    [_imgHello mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.lbTip.mas_top).offset(-5);
        make.centerX.equalTo(self.lbTip);
        make.width.mas_equalTo(136);
        make.height.mas_equalTo(52);
    }];
    
    _tfFullname.textColor = [UIColor whiteColor];
    Ivar ivar =  class_getInstanceVariable([UITextField class], "_placeholderLabel");
    UILabel *placeholderLabel = object_getIvar(_tfFullname, ivar);
    placeholderLabel.textColor = [UIColor whiteColor];
    _tfEmail.textColor = [UIColor whiteColor];
    _tfEmail.placeholder = @"code";
    placeholderLabel = object_getIvar(_tfEmail, ivar);
    placeholderLabel.textColor = [UIColor whiteColor];
    _tfMobile.textColor = [UIColor whiteColor];
    placeholderLabel = object_getIvar(_tfMobile, ivar);
    placeholderLabel.textColor = [UIColor whiteColor];
    _tfPwd.textColor = [UIColor whiteColor];
    placeholderLabel = object_getIvar(_tfPwd, ivar);
    placeholderLabel.textColor = [UIColor whiteColor];
    _tfMobile.keyboardType = UIKeyboardTypeNumberPad;
    
    _viewRegisterBg.backgroundColor = UIColorFromRGB(53, 53, 53);
    
    _lbLoginTip.textColor = [UIColor whiteColor];
    _lbLoginTip.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(registerLoginChange:)];
    [_lbLoginTip addGestureRecognizer:tap];
    
    [_btnSignup mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@44);
    }];
    [_btnSignup setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnSignup setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    UIImage *normalImg = [UIImage imageFromColor:UIColorFromRGB(255, 68, 74) size:_btnSignup.size];
    UIImage *highlightImg = [UIImage imageFromColor:[UIColor whiteColor] size:_btnSignup.size];
    [_btnSignup setBackgroundImage:normalImg forState:UIControlStateNormal];
    [_btnSignup setBackgroundImage:highlightImg forState:UIControlStateHighlighted];
    _btnSignup.clipsToBounds = YES;
    _btnSignup.layer.cornerRadius = 5;
    
    [_tfEmail mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.bottom.equalTo(_tfMobile.mas_top).offset(-50);
        make.height.mas_equalTo(@20);
    }];
    
    [_tfMobile mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.top.mas_equalTo(120);
        make.height.mas_equalTo(@20);
    }];
    
    [_tfFullname mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.top.equalTo(_tfMobile.mas_bottom).offset(50);
        make.height.mas_equalTo(@20);
    }];
    
    [_tfPwd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.top.equalTo(_tfMobile.mas_bottom).offset(120);
        make.height.mas_equalTo(@20);
    }];
    
    [_lbForgetPwd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_btnSignup.mas_right).offset(-50);
        make.bottom.equalTo(_btnSignup.mas_top).offset(-20);
        make.height.equalTo(@30);
    }];
    _lbForgetPwd.text = @"forget password?";
    _lbForgetPwd.textColor = [UIColor whiteColor];
//    _lbForgetPwd.backgroundColor = [UIColor redColor];
    
    UITapGestureRecognizer *tapForgetPwd = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(registerLoginChange:)];
    _lbForgetPwd.userInteractionEnabled = YES;
    [_lbForgetPwd addGestureRecognizer:tapForgetPwd];
}

- (void)registerLoginChange:(UITapGestureRecognizer *)gesture {
    if (gesture.view == _lbForgetPwd) {
        _viewType = ViewTypeForgetPwd;
        _lbForgetPwd.hidden = YES;
    } else {
        if (ViewTypeLogin == _viewType) {
            _viewType = ViewTypeRegister;
        } else {
            _viewType = ViewTypeLogin;
        }
    }
    
    [self updateUIDesc];
}

- (void)setupKeyboardManager {
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [[IQKeyboardManager sharedManager] setKeyboardDistanceFromTextField:60];
}

@end
